<template>
  <li
    @mouseenter="mouseHandler(true)"
    @mouseleave="mouseHandler(false)"
    :class="{ liStyle: mouseoverStyle }"
  >
    <label>
      <input type="checkbox" v-model="isCompleted" />
      <span>{{ todo.title }}</span>
    </label>
    <button class="btn btn-danger" v-show="isShow" @click="delTodo">删除</button>
  </li>
</template>
<script lang="ts">
import { computed, defineComponent, ref } from "vue";

import { Todo } from "../types/todo";

export default defineComponent({
  name: "Item",
  props: {
    todo: {
      type: Object as () => Todo, // 函数返回的是 Todo类型
      required: true
    },
    deleteTodo: {
      type: Function,
      required: true
    },
    index: {
      type: Number,
      required: true
    },
    updateTodo: {
      type: Function,
      required: true
    }
  },
  setup(props) {
    const mouseoverStyle = ref(false);
    const isShow = ref(false)
    const mouseHandler = (flag: boolean) => {
      if (flag) {
        mouseoverStyle.value = true;
        isShow.value = true;
      } else {
        mouseoverStyle.value = false;
        isShow.value = false;
      }
    };
    // 删除数据
    const delTodo = () => {
      if(window.confirm('确定要删除吗')) {
        props.deleteTodo(props.index)
      }
    }
    // 计算属性的方法 --来让当前的复选框选中
    const isCompleted = computed({
      get() {
        return props.todo.isCompleted
      },
      set(val) {
        // todo对象中的isCompleted来操作
        props.updateTodo(props.todo, val)
      }
    })
    return {
      mouseHandler,
      mouseoverStyle,
      isShow,
      delTodo,
      isCompleted
    };
  },
});
</script>
<style scoped>
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}
.liStyle {
  background-color: pink;
  color: white;
}
</style>